const app = getApp();
const MAX_COUNT_IMAGE = 1;
Page({
  data: {
    isExample: false, //是否展示示例
    authLocationTips: false,
    mainboard: [], //主板数量
    mainboardIndex: "", //选中的主板数量
    pageType: 1, // 1添加 2编辑
    equipment_name: "",
    equipmentTypes: [], //设备类型
    equipmentTypeIndex: "",
    equipment_number: "", //设备编号
    address: "",
    latitude: "",
    longitude: "",
    all_url_arrs: [],
    url_arrs: [],
    max_count_img: MAX_COUNT_IMAGE,

    mainboardConfig: [], //主板配置  [{equipment_name //主板名称 mainboard_num //主板编号, is_unfold //是否展开, config:[outlet_name //打水口名称,set_template_id 选中的打水模板id,template_title 选中的打水模板 template 打水模板]}]

    isFranchiser: false, //是否替加盟商在操作
    franchisers: [], //加盟商
    franchiserIndex: '', //选中的加盟商

    isRepair: false, //是否维修员
    partners: [], //合伙人
    partnerIndex: '', //选中的合伙人

    village: "", //存放园区数据对象
    template: "",
    open_nearby: false,
  },







  onLoad: function (options) {
    const pageType = options.type || 1;
    const isFranchiser = options.is_franchiser == 1 ? true : false;
    let title = pageType == 1 ? "设备添加" : "设备编辑";
    wx.setNavigationBarTitle({
      title,
    })

    if (pageType == 2) {
      this.equipment_id = options.equipment_id;
    }
    this.setData({
      isRepair: options.is_repair == 1 ? true : false,
      pageType,
      isFranchiser
    })
    if (!this.data.isFranchiser && !this.data.isRepair) { //合伙人
      Promise.all([
        this.fetchResult("Common/Common/getEquipmentType"),
        this.fetchResult("Common/Equipment/getEquipmentConfig"),
      ]).then(([equipmentTypes, mainboard]) => {
        this.setData({
          mainboard,
          equipmentTypes,
        })
        this.setDefault(pageType);
      })
    } else if (this.data.isFranchiser) { //加盟商
      Promise.all([
        this.fetchResult("Common/Common/getEquipmentType"),
        this.fetchResult("Common/Equipment/getEquipmentConfig"),
        this.fetchResult("Partner/Franchiser/franchiserList"),
      ]).then(([equipmentTypes, mainboard, franchisers]) => {
        this.setData({
          mainboard,
          equipmentTypes,
          franchisers
        })
        this.setDefault(pageType);
      })
    } else if (this.data.isRepair) {
      Promise.all([
        this.fetchResult("Common/Common/getEquipmentType"),
        this.fetchResult("Common/Equipment/getEquipmentConfig"),
        this.fetchResult("Manage/Equipment/getPartnerList"),
      ]).then(([equipmentTypes, mainboard, partners]) => {
        this.setData({
          mainboard,
          equipmentTypes,
          partners
        })
        this.setDefault(pageType);
      })
    }
  },

  switchChange(e) {
    this.setData({
      open_nearby: e.detail.value
    })
  },

  //跳转到园区选择界面
  navMiddleVillage() {
    let _self = this;

    let url = "../middle/village/index?none=0";
    if (this.data.isFranchiser) {
      if (_self.data.franchiserIndex === '') {
        app.showToast("请选择加盟商");
        return false;
      }
      url += "&is_franchiser=1"
    }
    if (this.data.isRepair) {
      if (_self.data.partnerIndex === '') {
        app.showToast("请选择合伙人");
        return false;
      }
      url += "&is_repair=1"
    }
    wx.navigateTo({
      url,
      events: {
        acceptDataFromMiddleVillage: function (data) {
          _self.setData({
            village: data,
            address: data.address,
            latitude: data.lat,
            longitude: data.lng,
          })
        }
      },
      success: res => {
        let datas = {
          village_id: _self.data.village.id
        }
        if (_self.data.isFranchiser) {
          datas.partner_id = _self.data.franchisers[_self.data.franchiserIndex].id
        }
        if (_self.data.isRepair) {
          datas.partner_id = _self.data.partners[_self.data.partnerIndex].id
        }
        res.eventChannel.emit('acceptDataFromOpenerPage', datas)
      }
    })
  },

  setTemplate(results) {
    this.setData({
      [`mainboardConfig[${this.tIndex}].config[${this.tSubIndex}].template_title`]: results.data.template_title,
      [`mainboardConfig[${this.tIndex}].config[${this.tSubIndex}].set_template_id`]: results.template_id,
      [`mainboardConfig[${this.tIndex}].config[${this.tSubIndex}].template`]: results.data.template,
    })
  },

  //跳转到选择打水模板界面
  navMiddleTemplate(e) {
    let _self = this;
    let {
      index,
      subindex
    } = e.currentTarget.dataset;
    this.tIndex = index;
    this.tSubIndex = subindex;
    let url = "../middle/template/index";
    if (this.data.isFranchiser) {
      if (_self.data.franchiserIndex === '') {
        app.showToast("请选择加盟商");
        return false;
      }
      url += "?is_franchiser=1";
    }
    if (this.data.isRepair) {
      if (_self.data.partnerIndex === '') {
        app.showToast("请选择合伙人");
        return false;
      }
      url += "?is_repair=1";
    }
    wx.navigateTo({
      url,
      events: {
        acceptDataFromMiddleTemplate: function (data) {
          _self.setData({
            [`mainboardConfig[${index}].config[${subindex}].template_title`]: data.template_title,
            [`mainboardConfig[${index}].config[${subindex}].set_template_id`]: data.id,
            [`mainboardConfig[${index}].config[${subindex}].template`]: data.template,
          })
        }
      },
      success: res => {
        let datas = {
          template_id: _self.data.mainboardConfig[index].config[subindex].set_template_id
        }
        if (_self.data.isFranchiser) {
          datas.partner_id = _self.data.franchisers[_self.data.franchiserIndex].id
        }
        if (_self.data.isRepair) {
          datas.partner_id = _self.data.partners[_self.data.partnerIndex].id
        }
        res.eventChannel.emit('acceptDataFromOpenerPage', datas)
      }
    })
  },


  //维修员选择合伙人
  handlePickerPartner(e) {
    const partnerIndex = this.data.partnerIndex;
    let value = e.detail.value;
    if (partnerIndex != value) {
      this.setData({
        partnerIndex: value,
        village: '',
        address: '',
        longitude: '',
        latitude: ''
      })
      const mainboardConfig = this.data.mainboardConfig;
      mainboardConfig.forEach(item => {
        if (item.config) {
          item.config.forEach(current => {
            if (current.set_template_id != 0) {
              current.set_template_id = 0;
              current.template_title = "平台默认模板";
            }
          })
        }
      });
      this.setData({
        mainboardConfig
      })
    }
  },


  //合伙人选择加盟商
  handlePickerFranchiser(e) {
    const franchiserIndex = this.data.franchiserIndex;
    let value = e.detail.value;
    if (franchiserIndex != value) {
      this.setData({
        franchiserIndex: value,
        village: '',
        address: '',
        latitude: '',
        longitude: ''
      })
      const mainboardConfig = this.data.mainboardConfig;
      mainboardConfig.forEach(item => {
        if (item.config) {
          item.config.forEach(current => {
            if (current.set_template_id != 0) {
              current.set_template_id = 0;
              current.template_title = "平台默认模板";
            }
          })
        }
      });
      this.setData({
        mainboardConfig
      })
    }
  },



  //设置默认数据
  setDefault(pageType) {
    if (pageType == 1) { //添加默认选中第一个主板数量
      let val = 0;
      let mainboard = this.data.mainboard[val];
      let configs = [];
      for (let i = 0; i < mainboard.equipment_quantity; i++) {
        configs.push({
          equipment_name: '',
          mainboard_num: "",
          is_unfold: false
        })
      }
      this.lastMainboardConfig = JSON.parse(JSON.stringify(configs));
      this.setData({
        mainboardConfig: configs,
        mainboardIndex: 0
      })
    }
    if (pageType == 2) {
      if (!this.data.isFranchiser && !this.data.isRepair) {
        this.getEquipment();
      } else if (this.data.isFranchiser) {
        this.getFranchiserEquipment();
      } else if (this.data.isRepair) {
        this.getRepairEquipment();
      }
    }
  },






  //选择设备分类
  chooseMainboard(e) {
    const val = Number.parseInt(e.detail.value);
    if (val !== this.data.mainboardIndex) {
      let mainboard = this.data.mainboard[val];
      let configs = [];
      for (let i = 0; i < mainboard.equipment_quantity; i++) {
        configs.push({
          mainboard_num: "",
          is_unfold: false
        })
      }
      this.lastMainboardConfig = JSON.parse(JSON.stringify(configs));
      this.setData({
        mainboardConfig: configs,
      })
    }
    this.setData({
      mainboardIndex: val
    })
  },


  scanMianboardCode(e) {
    const index = e.currentTarget.dataset.index;
    app.scanDeviceCode().then(res => {
      this.setData({
        [`mainboardConfig[${index}].mainboard_num`]: res,
      })
    })
  },


  //收起主板配置
  fewerMainboardConfig(e) {
    const {
      index
    } = e.currentTarget.dataset;
    this.setData({
      [`mainboardConfig[${index}].is_unfold`]: false,
    })
  },

  showMainboardConfig(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.pageType == 2) {
      this.setData({
        [`mainboardConfig[${index}].is_unfold`]: true,
      })
    } else {
      let mainboardConfig = this.data.mainboardConfig;
      let mainboard_num = mainboardConfig[index].mainboard_num;
      if (mainboard_num == "") {
        app.showToast("请输入主板编号");
        return false;
      }
      //检查下编号和上次存放的记录是否一直 如果一样就直接展开
      if (this.lastMainboardConfig && this.lastMainboardConfig.length > 0) {
        if (this.lastMainboardConfig[index].mainboard_num == mainboardConfig[index].mainboard_num) {
          this.setData({
            [`mainboardConfig[${index}].is_unfold`]: true,
          })
          return;
        }
      }
      //遍历下该主板编号是否已经存在
      let is_exist = 0;
      for (let i = 0; i < mainboardConfig.length; i++) {
        if (mainboardConfig[i].mainboard_num == mainboard_num) {
          ++is_exist;
        }
      }
      if (is_exist >= 2) {
        app.showToast("不能录入相同主板");
        return;
      }
      app.ajax({
        url: "Common/Equipment/getEquipmentMainboardType",
        data: {
          equipment_number: mainboard_num
        },
        success: res => {
          if (res.data.code === 1000) {
            const outlet_number = res.data.data.outlet_number;
            let configs = [];
            for (let i = 0; i < outlet_number; i++) {
              let set_template_id = '',
                template_title = '',
                template = '';
              let village = this.data.village;
              if (village != '' && this.data.id != '') {
                set_template_id = village.online_water_drawing_template_id;
                template = village.set_template_id;
                template_title = village.template_title;
              }
              configs.push({
                outlet_name: "",
                set_template_id,
                template_title,
                template
              })
            }
            this.lastMainboardConfig[index].mainboard_num = mainboard_num;
            this.setData({
              [`mainboardConfig[${index}].config`]: configs,
              [`mainboardConfig[${index}].is_unfold`]: true,
            })
          } else {
            app.showToast(res.data.message);
          }
        },
        error: e => {
          app.showToast("网络错误");
        }
      })
    }

  },


  //监听主板编号录入
  handleMainboardInput(e) {
    const value = e.detail.value;
    let index = e.currentTarget.dataset.index;
    this.setData({
      [`mainboardConfig[${index}].mainboard_num`]: value,
    })
  },

  handleMainboardName(e) {
    const value = e.detail.value;
    let index = e.currentTarget.dataset.index;
    this.setData({
      [`mainboardConfig[${index}].equipment_name`]: value,
    })
  },



  //监听打水口名称监听
  handleInputOutlet(e) {
    const value = e.detail.value;
    let {
      index,
      subindex
    } = e.currentTarget.dataset;
    this.setData({
      [`mainboardConfig[${index}].config[${subindex}].outlet_name`]: value,
    })
  },



  scanCode(e) {
    const name = e.currentTarget.dataset.name;
    app.scanDeviceCode().then(res => {
      this.setData({
        [name]: res
      })
    }).catch(e => {
      app.showToast("扫码失败")
    })
  },


  //维修员设备详情处理
  getRepairEquipment() {
    app.ajax({
      url: 'Manage/Equipment/detail',
      data: {
        equipment_control_id: this.equipment_id
      },
      success: res => {
        if (res.data.code > 0) {
          const source = res.data.data;
          //根据合伙人的id获取对应的园区和打水模板
          let partner_id = source.partner_id;
          Promise.all([this.fetchResult("Manage/Template/templateList", {
            page: 1,
            row: 999,
            template_species: "2",
            is_add_global_template: true,
            partner_id
          })]).then(([templateRes]) => {
            console.log(templateRes, "templateRes");
            let templates = templateRes.data
            let equipmentTypeIndex = this.data.equipmentTypes.findIndex(item => item.id == source.equipment_control_type_id);
            let mainboardIndex = this.data.mainboard.findIndex(item => item.id == source.equipment_quantity_id);
            let partnerIndex = this.data.partners.findIndex(item => item.id == partner_id);
            const equipment_info = source.equipment_info;
            let mainboardConfig = [];
            equipment_info.forEach(item => {
              let origin = item.outlet_data;
              let config = [];
              origin.forEach(current => {
                let templateIndex = templates.findIndex(element => element.id == current.set_template_id)
                config.push({
                  outlet_name: current.outlet_name,
                  template_title: ~templateIndex ? templates[templateIndex].template_title : '',
                  set_template_id: ~templateIndex ? templates[templateIndex].id : '',
                  template: ~templateIndex ? templates[templateIndex].template : '',
                });
              })
              mainboardConfig.push({
                mainboard_num: item.equipment_number,
                is_unfold: false,
                config,
              })
            });
            let village = {
              id: source.village_id,
              province_name: source.province_name,
              city_name: source.city_name,
              area_name: source.area_name,
              province: source.province,
              city: source.city,
              area: source.area,
              village_name: source.village_name,
            }
            this.setData({
              village,
              equipment_name: source.name,
              address: source.address,
              equipmentTypeIndex: ~equipmentTypeIndex ? equipmentTypeIndex : "",
              mainboardIndex: ~mainboardIndex ? mainboardIndex : "",
              partnerIndex: ~partnerIndex ? partnerIndex : "",
              url_arrs: source.equipment_img,
              all_url_arrs: source.equipment_img_whole,
              longitude: source.longitude,
              latitude: source.latitude,
              mainboardConfig
            })
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },




  //加盟商设备详情处理
  getFranchiserEquipment() {
    app.ajax({
      url: 'Partner/Equipment/detail',
      data: {
        equipment_control_id: this.equipment_id
      },
      success: res => {
        if (res.data.code > 0) {
          const source = res.data.data;
          //根据加盟商的id获取对应的园区和打水模板
          let partner_id = source.partner_id;
          Promise.all([this.fetchResult("Partner/Village/templateList", {
            page: 1,
            row: 999,
            template_species: "2",
            is_add_global_template: true,
            partner_id
          })]).then(([templatesRes]) => {
            let templates = templatesRes.data;
            let equipmentTypeIndex = this.data.equipmentTypes.findIndex(item => item.id == source.equipment_control_type_id)
            let mainboardIndex = this.data.mainboard.findIndex(item => item.id == source.equipment_quantity_id);
            let franchiserIndex = this.data.franchisers.findIndex(item => item.id == partner_id);
            const equipment_info = source.equipment_info;
            let mainboardConfig = [];
            equipment_info.forEach(item => {
              let origin = item.outlet_data;
              let config = [];
              origin.forEach(current => {
                let templateIndex = templates.findIndex(element => element.id == current.set_template_id)
                config.push({
                  outlet_name: current.outlet_name,
                  template_title: ~templateIndex ? templates[templateIndex].template_title : '',
                  set_template_id: ~templateIndex ? templates[templateIndex].id : '',
                  template: ~templateIndex ? templates[templateIndex].template : '',
                });
              })
              mainboardConfig.push({
                mainboard_num: item.equipment_number,
                is_unfold: false,
                config,
              })
            });
            //园区数据组装
            let village = {
              id: source.village_id,
              province_name: source.province_name,
              city_name: source.city_name,
              area_name: source.area_name,
              province: source.province,
              city: source.city,
              area: source.area,
              village_name: source.village_name,
            }
            this.setData({
              equipment_name: source.name,
              address: source.address,
              village,
              equipmentTypeIndex: ~equipmentTypeIndex ? equipmentTypeIndex : "",
              mainboardIndex: ~mainboardIndex ? mainboardIndex : "",
              franchiserIndex: ~franchiserIndex ? franchiserIndex : "",
              url_arrs: source.equipment_img,
              all_url_arrs: source.equipment_img_whole,
              longitude: source.longitude,
              latitude: source.latitude,
              mainboardConfig
            })
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },


  //合伙人设备详情处理
  getEquipment() {
    app.ajax({
      url: 'Partner/Equipment/detail',
      data: {
        equipment_control_id: this.equipment_id
      },
      success: res => {
        if (res.data.code > 0) {
          const source = res.data.data;
          this.fetchResult("Partner/Village/templateList", {
            page: 1,
            row: 999,
            template_species: "2",
            is_add_global_template: true,
          }).then(templateRes => {
            let templates = templateRes.data;
            let equipmentTypeIndex = this.data.equipmentTypes.findIndex(item => item.id == source.equipment_control_type_id)

            let mainboardIndex = this.data.mainboard.findIndex(item => item.id == source.equipment_quantity_id);
            const equipment_info = source.equipment_info;
            let mainboardConfig = [];
            equipment_info.forEach(item => {
              let origin = item.outlet_data;
              let config = [];
              origin.forEach(current => {
                let templateIndex = templates.findIndex(element => element.id == current.set_template_id)
                config.push({
                  outlet_name: current.outlet_name,
                  template_title: ~templateIndex ? templates[templateIndex].template_title : '',
                  set_template_id: ~templateIndex ? templates[templateIndex].id : '',
                  template: ~templateIndex ? templates[templateIndex].template : '',
                });
              })
              mainboardConfig.push({
                equipment_name: item.equipment_name,
                mainboard_num: item.equipment_number,
                is_unfold: false,
                config,
              })
            });

            //园区数据组装
            let village = {
              id: source.village_id,
              province_name: source.province_name,
              city_name: source.city_name,
              area_name: source.area_name,
              province: source.province,
              city: source.city,
              area: source.area,
              village_name: source.village_name,
            }
            this.setData({
              village,
              equipment_name: source.name,
              address: source.address,
              equipmentTypeIndex: ~equipmentTypeIndex ? equipmentTypeIndex : "",
              mainboardIndex: ~mainboardIndex ? mainboardIndex : "",
              url_arrs: source.equipment_img,
              all_url_arrs: source.equipment_img_whole,
              longitude: source.longitude,
              latitude: source.latitude,
              mainboardConfig,
              open_nearby: source.open_nearby == 1 ? true : false
            })
          }).catch(e => {
            app.showToast(e)
          });

        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },


  chooseImg() {
    let pictrues = this.data.all_url_arrs;
    let count = MAX_COUNT_IMAGE - pictrues.length;
    wx.chooseImage({
      sizeType: ["compressed"],
      count,
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '资源上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          this.uploadFile(tempFilePaths[i], i, tempFilePaths.length - 1);
        }
      }
    })
  },

  uploadFile: function (tempFilePath, i, len) {
    var that = this;
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePath,
      name: 'file',
      success(res) {
        var source = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}");
        if (source.code == 1000) {
          let all_url_arrs = that.data.all_url_arrs;
          let url_arrs = that.data.url_arrs;
          url_arrs.unshift(source.data.url);
          all_url_arrs.unshift(source.data.all_url);
          console.log(all_url_arrs, url_arrs);
          if (i == len) {
            wx.hideLoading();
          }
          that.setData({
            all_url_arrs,
            url_arrs
          })
        } else {
          app.showToast(`第${i+1}张图片上传失败`);
        }
      }
    })
  },

  deleteImg(e) {
    const index = e.currentTarget.dataset.index;
    let all_url_arrs = this.data.all_url_arrs;
    let url_arrs = this.data.url_arrs;
    all_url_arrs.splice(index, 1)
    url_arrs.splice(index, 1)
    this.setData({
      all_url_arrs,
      url_arrs
    })
  },

  navMapSetting() {
    if (this.data.village === "" || this.data.village.id == '') {
      app.showToast("请先选择园区", "none", 2000, function () {});
      return;
    }
    wx.getSetting({
      success: settingRes => {
        if (settingRes.errMsg === "getSetting:ok") {
          const setting = settingRes.authSetting;
          if (setting["scope.userLocation"] == undefined || setting["scope.userLocation"]) {
            if (!this.data.latitude || !this.data.longitude) {
              wx.getLocation({
                type:"gcj02",
                success: results => {
                  this.setData({
                    latitude: results.latitude,
                    longitude: results.longitude
                  })
                  this.openLocation();
                },
                fail: res => {
                  app.showToast("请检查是否打开手机定位功能");
                }
              })
            } else {
              this.openLocation();
            }
          } else if (setting["scope.userLocation"] == false) {
            this.setData({
              authLocationTips: true
            })
          }
        }
      },
      fail: e => {
        app.showToast("getSetting fail");
      }

    })
  },

  openLocation() {
    wx.chooseLocation({
      latitude: this.data.latitude - 0,
      longitude: this.data.longitude - 0,
      success: res => {
        if (res.errMsg === "chooseLocation:ok") {
          this.setData({
            address: res.name,
            longitude: res.longitude,
            latitude: res.latitude
          })
        }
      },
      fail: e => {
        if (e.errMsg === "chooseLocation:fail auth deny") {
          this.setData({
            authLocationTips: true
          })
        }
      }
    })
  },

  handleOpenSetting() {
    wx.openSetting({
      success: res => {
        if (res.errMsg === "openSetting:ok") {
          if (res.authSetting["scope.userLocation"]) {
            this.setData({
              authLocationTips: false
            })
            this.openLocation()
          }
        }
      },
      fail: e => {
        app.showToast("打开设置失败");
      }
    })
  },


  closeLocationTips() {
    this.setData({
      authLocationTips: false
    })
  },

  handlePicker(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },



  fetchResult(url, data = {}) {
    return new Promise((resolve, reject) => {
      app.ajax({
        url,
        data,
        success: res => {
          if (res.data.code > 0) {
            resolve(res.data.data);
          } else {
            app.showToast(res.data.message);
          }
        },
        error: e => {
          app.showToast("网络错误");
        }
      })
    })
  },

  //提交数据
  formSubmit(e) {
    const formData = e.detail.value;
    const equipmentTypeIndex = this.data.equipmentTypeIndex;
    let isFranchiser = this.data.isFranchiser;

    if (formData.equipment_name === "") {
      app.showToast("请输入设备名称");
      return false;
    }
    if (equipmentTypeIndex === "") {
      app.showToast("请选择设备类型");
      return false;
    }

    if (isFranchiser) {
      if (this.data.franchiserIndex === '') {
        app.showToast("请选择加盟商");
        return false;
      }
    }

    if (this.data.isRepair) {
      if (this.data.partnerIndex === '') {
        app.showToast("请选择合伙人");
        return false;
      }
    }


    if (formData.equipment_number === "") {
      app.showToast("缺少设备编号");
      return false;
    }
    if (this.data.village == "" || this.data.village.id == "") {
      app.showToast("请选择园区");
      return false;
    }

    if (formData.address === "") {
      app.showToast("缺少安装地址");
      return false;
    }

    const mainboardConfig = this.data.mainboardConfig;
    let equipment_data = [];
    for (let i = 0; i < mainboardConfig.length; i++) {
      if (mainboardConfig[i].mainboard_num == "") {
        app.showToast(`主板编号未填写`);
        return false;
      }
      let outlet_data = [];
      let config = mainboardConfig[i].config;
      if (config) {
        for (let j = 0; j < config.length; j++) {
          if (config[j].set_template_id === "") {
            app.showToast(`请选择线上打水配置`);
            return false;
          }
          outlet_data.push({
            name: config[j].outlet_name,
            set_template_id: config[j].set_template_id
          })
        }
      }
      equipment_data.push({
        equipment_name: mainboardConfig[i].equipment_name,
        equipment_number: mainboardConfig[i].mainboard_num,
        outlet_data,
      });
    }


    let url = "Partner/Equipment/add";
    if (this.data.pageType == 2) {
      formData.equipment_control_id = this.equipment_id;
      url = "Partner/Equipment/edit";
    }

    //维修员
    if (this.data.isRepair) {
      if (this.data.pageType == 1) {
        url = "Manage/Equipment/add";
        formData.equipment_control_id = this.equipment_id;
        formData.s_number = this.data.partners[this.data.partnerIndex].s_number
      } else {
        url = "Manage/Equipment/edit";
      }
    }

    let latitude = this.data.latitude;
    let longitude = this.data.longitude;
    if (!latitude || !longitude || latitude == "0" || longitude == "0") {
      app.showToast("请点击定位图标重新定位");
      return false;
    }

    Object.assign(formData, {
      name: formData.equipment_name,
      type: 0,
      longitude,
      latitude,
      village_id: this.data.village.id,
      address: this.data.address,
      equipment_quantity_id: this.data.mainboard[this.data.mainboardIndex].id, // 主板数量ID
      province: this.data.village.province,
      city: this.data.village.city,
      area: this.data.village.area,
      province_name: this.data.village.province_name,
      city_name: this.data.village.city_name,
      area_name: this.data.village.area_name,
      equipment_control_type_id: this.data.equipmentTypes[equipmentTypeIndex].id, //设备类型
      equipment_img: this.data.url_arrs, //设备图片
      equipment_data, //主板信息
      open_nearby: this.data.open_nearby ? 1 : 2
    })

    if (isFranchiser) {
      Object.assign(formData, {
        isfranchiser: 1,
        type: 1,
        partner_id: this.data.franchisers[this.data.franchiserIndex].id
      })
    }

    app.ajax({
      url,
      data: formData,
      success: res => {
        wx.hideLoading();
        if (res.data.code > 0) {
          app.showToast(res.data.message, "success")
          setTimeout(() => {
            let pages = getCurrentPages();
            let targetPage = pages[pages.length - 2];
            console.log(targetPage);
            if (targetPage.hasOwnProperty("reloadData")) {
              targetPage.reloadData();
            }
            wx.navigateBack()
          }, 1500)
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网路错误");
      }
    })
  },


  lookExample() {
    this.setData({
      isExample: true
    })
  },

  hiddenExmple() {
    this.setData({
      isExample: false
    })
  },
})